//
//  WKViewController.swift
//  WebViewGoback
//
//  Created by 郑东喜 on 2017/2/23.
//  Copyright © 2017年 郑东喜. All rights reserved.
//  WkwebView

import UIKit
import WebKit

class WKViewController: UIViewController {
    
    fileprivate lazy var webView: WKWebView = {
        let w : WKWebView = WKWebView.init(frame: self.view.bounds)
        w.navigationDelegate = self;
        return w
    }()
    
    
    //前进
    lazy var forwardBar: UIBarButtonItem = {
        let rightBar : UIBarButtonItem = UIBarButtonItem.init(title: "前进", style: .plain, target: self, action: #selector(self.rightBarSel))
        return rightBar
    
    }()
    
    //后退
    fileprivate lazy var leftBar: UIBarButtonItem = {
        let leftbar : UIBarButtonItem = UIBarButtonItem.init(title: "返回", style: .plain, target: self, action: #selector(self.leftBarSEL))
        return leftbar
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.prepareUI()
        
        self.navigationItem.leftBarButtonItem = leftBar
        self.navigationItem.rightBarButtonItem = forwardBar
    }
}


extension WKViewController {
    /// 准备shitu
    fileprivate func prepareUI() -> Void {
        
        view.addSubview(self.webView)
        self.webView.load(URLRequest.init(url: URL.init(string: "https://www.baidu.com/")!))
    }
}


extension WKViewController {
    ///前进
     @objc fileprivate func rightBarSel() -> Void {
        if self.webView.canGoForward == true {
            self.webView.goForward()
        } else {}
    }
    ///后退
    @objc fileprivate func leftBarSEL() -> Void {
        if self.webView.canGoBack == true {
            self.webView.goBack()
        } else {
            self.navigationController?.popViewController(animated: true)
        }
    }
}

// MARK:- WKNavigationDelegate
extension WKViewController : WKNavigationDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.title = webView.title
    }
}
